<?php
/* $Id: browse.php 20 2009-12-04 22:50:33Z ronan $ */
$basesite=$_SERVER['PHP_SELF'];
require("common.php");
require("auth.php");
require("header.php");
$marketGroup= (isset($_GET['marketgroup'])?$_GET['marketgroup']:null);
$hastypes=(isset($_GET['hastypes'])?$_GET['hastypes']:null);
$blueprintOptions=($userLevel=='producer' || $userLevel=='producertrader' || $userLevel=='admin' || $userLevel=='headproducer');
if(isset($_GET['f'])&&$_GET['f']=='addbp') {
	if(!isset($_GET['typeid'])) {
		echo "Cannot add blueprint - no id specified to add!<br /><br />\n\n";
	} else {
		$typeID=$_GET['typeid'];
		$bp=Query("SELECT * FROM producerblueprints WHERE producerID=$uidnum AND typeID=$typeID LIMIT 1");
		if(mysql_num_rows($bp)!=0) {
			echo "You already have this blueprint in your library - you can't add it again.<br /><br />\n\n";
		} else {
			$result=Query("INSERT INTO producerblueprints(`typeID`, `producerID`) VALUES($typeID, $uidnum)");
			echo "Added blueprint to library.<br /><br />\n\n";
		}
	}
}
if(isset($_GET['f'])&&$_GET['f']=='removebp') {
	if(!isset($_GET['typeid'])) {
		echo "Cannot remove blueprint - no id specified to remove!<br /><br />\n\n";
	} else {
		$typeID=$_GET['typeid'];
		$bp=Query("SELECT * FROM producerblueprints WHERE producerID=$uidnum AND typeID=$typeID LIMIT 1");
		if(mysql_num_rows($bp)==0) {
			echo "You do not have this blueprint in your library. You cannot remove it yet!<br /><br />\n\n";
		} else {
			$result=Query("DELETE FROM producerblueprints WHERE typeID=$typeID AND producerID=$uidnum LIMIT 1");
			echo "Removed blueprint from library.<br /><br />\n\n";
		}
	}
}
if(isset($_POST['cart'])) {
	$id=$_POST['id'];
	$qty = stripCommas($_POST['qty']);
	$specialorder=(isset($_POST['specialorder'])?2:0);
	
	$item = getItemById($id);
	$quantityModifier = mysql_result($item,0,'quantityModifier');
	$name=mysql_result($item, 0, 'typeName');
	//escape any single qoutes
	$name=str_replace("'","''", $name);
	$price=mysql_result($item, 0, 'price');
	$numAvailable=mysql_result($item, 0, 'numAvailable');
	$isBuildable=mysql_result($item,0,'isBuildable');
	$isSpecialOrderable = mysql_result($item,0,'isSpecialOrderable');
	$orders=Query("SELECT * FROM orders WHERE customerID=$uidnum AND status='in cart'");
	$q=0; $err=0;
	if(!is_number($qty) || $qty<1 || $qty>$maxQuantity) {
		echo "ERROR: bad quantity!";
		require("footer.php");
		exit;
	}
	while($l=mysql_fetch_array($orders)) {
		if( $id==$l['typeID'] ) {
			$newqty = $qty+$l['quantity'];
			if($newqty>$maxQuantity) { echo "ERROR: Adding $qty of this item leaves your cart with more of this item than the allowable maximum. Not added."; require("footer.php"); exit; }
			if(!$isSpecialOrderable && !$isBuildable && $newqty>$numAvailable) { echo "ERROR: We cannot special order this item, and adding $qty of this item leaves your cart with more of this item than we have available. Not added."; $err=1; $q=1; break; }
			$results = Query("UPDATE orders SET quantity=quantity+".$qty.", priceTotal=pricePerUnit*quantity WHERE id='".$l['id']."' LIMIT 1");
			$q=1;
			break;
		}
	}
	if($q!=1 && !$isSpecialOrderable && !$isBuildable && $numAvailable<=0) {
		echo "You can't actually order this item - we can't build it, can't special order it, and don't have any stock of it. If you see this message at all, it's actually a bug - it shouldn't have even shown up in the browse page. Please let Phantom Circuit know :)<br />\n";
		$err=1; $q=1;
	}
	else if($q!=1 && !$isSpecialOrderable && !$isBuildable && $numAvailable>0 && $qty>$numAvailable) {
		echo "We cannot special order this item, so you can only buy as many we have in stock - $numAvailable added to cart.";
		$qty = $numAvailable;
	} 
	else if(!$err) echo "$qty x $quantityModifier \"$name\"".($qty*$quantityModifier==1?' has':'s have')." been added to the cart.<br />\n";
	if(!$q) $results = Query("INSERT INTO orders (typeId, typeName, quantity, quantityModifier, pricePerUnit, priceTotal, customerID, customerName, status, usingStock) VALUES('$id', '$name', '$qty', '$quantityModifier', '$price', '".($price*$qty)."', '$uidnum', '$uid', 'in cart', '$specialorder')");
	if($qty > $numAvailable && !$isBuildable && $isSpecialOrderable) {
		if($numAvailable<=0) echo 'This is a <font color="yellow">special order</font>.<br />'."\n";
		else echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock, so the rest will be converted into a ".($isBuildable?'build order.':'<font color="yellow">special order</font>.')."<br />\n";
	} else if($qty > $numAvailable && $isBuildable && $numAvailable>0) echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock, so the rest will be converted into a ".($isBuildable?'build order.':'<font color="yellow">build order</font>.')."<br />\n";
	echo "<br />\n";	
}
echo "Find an item: <form method=\"GET\" action=\"browse.php\"><input type=\"text\" size=\"20\" name=\"q\" /><input type=\"submit\" value=\"Search\" /></form><br />\n";
if(!empty($_GET['q'])) {
	$q = $_GET['q'];
	$q = str_replace("'","''", $q);
	echo "<a href=\"browse.php\">Index</a><br />\n";
	if(strlen($q)<3) {echo "Please, think of the poor database! Use a search of at least 3 characters."; require("footer.php"); exit; }
	//$items = Query("SELECT * FROM items WHERE marketGroupID IS NOT NULL AND typeName LIKE '%".$q."%' AND (numAvailable>'0' OR isSpecialOrderable='1' OR isBuildable='1') ORDER BY typeName ASC");
	$items = searchItemsBySubString($q);
	
	//echo "Note that for the sake of not killing the database, only the first 25 results can be shown. Use a more specific search if you don't see what you're looking for.<br /><br />\n";
	if(!mysql_num_rows($items)) return "No items found that include the phrase \"$q\"!<br />\n";
	$r='';
	$i=0;
	$r.= "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Quantity</b></td>".($blueprintOptions?"<td><b>Options</b></td>":'')."</tr>\n";
	while ($l = mysql_fetch_array($items, MYSQL_ASSOC)) {
		$cmid = $l['marketGroupID'];
		$cont=0;
		while($cmid!="NULL" && $cmid!="") {
			$mg = getMarketGroupById($cmid);
			if(mysql_result($mg, 0, 'isBuildable')==0) {$cont=1; break;}
			$cmid=mysql_result($mg,0,'parentGroupID');
		}

		//if the item is not buildable, don't list it.
		if($cont) continue;
		
		$typeID=$l['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
		
		$r.=($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
		$r .= 	"<!--ID: ".$l['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="javascript:CCPEVE.showInfo('.$l['typeID'].')">':'').$l['typeName'].($ingame?'</a>':'')."</td>\t";
		
		$r.="<td width=\"125\">".addCommas($l['price'])." per ".addCommas($l['quantityModifier'])."</td>\t"; 
		$r.="<td width=\"125\">";
		$r.= displayAvailability($l['numAvailable'],$l['isBuildable'],$l['isSpecialOrderable']);
		$r.="</td>\t";	

		if($l['numAvailable']<=0 && $l['isBuildable']==0 && $l['isSpecialOrderable']==0) {$r.="<td width=\"150\">&nbsp;</td>";}
		else if($l['numAvailable']<=0 && $l['isBuildable']==0)  {
			$r .= "<td width=\"150\"><form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?q=".str_replace(" ", "+", $q)."\">" .
				generateHiddenFields(array("marketgroup"=>$marketGroup, "hastypes"=>"1", "cart"=>1, "specialorder"=>1, "id"=>$l['typeID'], "name"=>str_replace(" ", "_",$l['typeName']), "price"=>$l['price'])) .
				"<input type=\"text\" name=\"qty\" size=\"6\" value=\"1\" />".($l['quantityModifier']==1?'':"x".addCommas($l['quantityModifier']))."<input type=\"submit\" value=\"Special Order\" /></form></td>\t";
		} 
		else $r .= "<td align=\"left\" width=\"150\"><form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?q=".str_replace(" ", "+", $q)."\">" .
			generateHiddenFields(array("marketgroup"=>$marketGroup, "hastypes"=>"1", "cart"=>1, "id"=>$l['typeID'], "name"=>str_replace(" ", "_",$l['typeName']), "price"=>$l['price'])) .
			"<input type=\"text\" name=\"qty\" size=\"6\" value=\"1\" />".($l['quantityModifier']==1?'':"x".addCommas($l['quantityModifier']))."<input type=\"submit\" value=\"Add to cart\" /></form></td>\t";		
		
		if($blueprintOptions) {
			$hasBP=mysql_num_rows(Query("SELECT * FROM producerblueprints WHERE typeID=".$l['typeID']." AND producerID=$uidnum LIMIT 1"));
			$r.="<td width=\"175\"><a href=\"browse.php?f=".($hasBP?'remove':'add')."bp&marketgroup=$marketGroup&hastypes=1&q=".str_replace(" ", "+", $q)."&typeid=".$l['typeID']."\">".($hasBP?'Remove from':'Add to')." BP library</a></td>";
		}
		
		$r .= "</tr>\n";
		$i++;
	}
	$r.="</table>\n";
	echo $r;
	require("footer.php");
	exit;
}
echo getMarketPath(isset($marketGroup)?$marketGroup:null) . "<br /><br />\n\n";
echo getMarketGroup(isset($marketGroup)?$marketGroup:null, isset($hastypes)?$hastypes:null);
require("footer.php");
?>